<?php
namespace Api\Controller;

class AppTopicController extends PublicController 
{
    /**
     * 获取所有的栏目信息
     * @author liubo <liubo@ilongyuan.com.cn>
     */
    public function all()
    {
        $this->list_success(event('AppTopic')->lists());
    }

    /**
     * 获取用户的栏目
     * @author liubo <liubo@ilongyuan.com.cn>
     */
    public function mine()
    {
        $this->checkLogin();
        $this->list_success(event('AppTopic')->getUserTopics(UID));
    }

    /**
     * 设置用户的栏目信息
     * @author liubo <liubo@ilongyuan.com.cn>
     * @param  string $ids
     */
    public function set($ids = '')
    {
        if (!$ids) {
            $this->param_error();
        }
        $this->checkLogin();
        $ids = array_map('intval', explode(',', $ids));
        event('AppTopic')->setUserTopics(UID, $ids);
        $this->success();
    }

    /**
     * 首页栏目下的数据列表
     * @author liubo <liubo@ilongyuan.com.cn>
     */
    public function lists()
    {
        $topic = I('type');
        if (empty($topic)) {
            $this->success();
        }

        $this->uid = 0;
        $appToken = I('appToken', '', 'trim');
        $appToken && $this->uid = $this->getUid($appToken);
        $this->games = [];
        $this->uids = [];

        if (!empty($this->uid)) {
            $this->games = event('GameScribe')->mine($this->uid);
            $this->uids = [];//event('Follow')->mine($this->uid);
        } else {
            $games = I('games', '', 'trim');
            $games = $games ? explode(',', $games) : [];
            $this->games = array_map('intval', $games);
        }
        $timestamp = I('timestamp', '');
        $p = I('p', 1, 'intval');
        $limit = I('limit', 10, 'intval');
        // $limit最大值20
        $limit > 20 && $limit = 20;

        $list = [];
        switch ($topic) {
            case 'follow':
                $list = $this->follow($timestamp, $limit);
                break;
            case 'hot':
                $list = $this->hot($p, $limit);
                break;
            case 'recommend':
                $list = $this->recommend($p, $limit);
                break;
            case 'news':
                $list = $this->news($p, $limit);
                break;
            case 'circle':
                $list = $this->circle($p, $limit);
                $this->success('', $list);
                break;
            default:
                $this->param_error();
                break;
        }
        $this->list_success($list);
    }

    /**
     * 关注
     * @author liubo <liubo@ilongyuan.com.cn>
     * @param  string  $timestamp [description]
     * @param  integer $limit     [description]
     */
    private function follow($timestamp = '', $limit = 10)
    {
        $query = [];
        if (!empty($timestamp)) {
            $query['pub_time'] = ['$lt' => strval($timestamp)]; // 资源表中pub_time是string
        }

        $res = event('ResourceGroup')->lists($this->games, $this->uids, $query, $limit, 'object_id,object_type,pub_time');
        return $this->_format($res);
    }

    /**
     * 热门
     * @author liubo <liubo@ilongyuan.com.cn>
     * @param  integer $p     [description]
     * @param  integer $limit [description]
     */
    private function hot($p = 1, $limit = 10)
    {
        $random = I('random', 0, 'intval');
        if ($random) {
            $vids = event('VideoHot')->getRandom($this->games, $start = 50, $end = 500, $limit);
        } else {
            $vids = event('VideoHot')->getData($this->games, $p, $limit);
        }

        $res = array_map(function($id){return ['object_id' => $id, 'object_type' => 0];}, $vids);

        return $this->_format($res);
    }

    /**
     * 资讯
     * @author liubo <liubo@ilongyuan.com.cn>
     * @param  integer $p     [description]
     * @param  integer $limit [description]
     */
    private function news($p = 1, $limit = 10)
    {
        $map = ['type' => 0, 'status' => 1, 'create_time' => ['$lt' => NOW_TIME]];
        if (!empty($this->games)) {
            $map['game_id'] = ['$in' => $this->games];
        }
        $res = service('News')->where($map)->page($p)->limit($limit)->order('create_time desc')->getField('id', true);
        $res = array_map(function($id){return ['object_id' => $id, 'object_type' => 2];}, $res);

        return $this->_format($res);
    }

    /**
     * 精选
     * @author liubo <liubo@ilongyuan.com.cn>
     */
    private function recommend($p = 1, $limit = 10)
    {
        $res = event('Video')->getDailyRecommentVids($p, $limit);
        foreach ($res as &$value) {
            $video = event('Video')->detail($value['video_id'], $this->uid);
            if ($video && $video['status'] != -1) {
                if ($value['cover']) {
                    uri_format($value['cover']);
                    $video['thumb'] = $value['cover'];
                }
                $value['video'] = $video;
                $dailys[] = $value;
            }
        }
        $dailys = field_filter($dailys, ['date', 'reason', 'video'], true);
        $group = [];
        foreach ($dailys as $key => $value) {
            if (!array_key_exists($value['date'], $group))
            {
                $group[$value['date']] = ['date' => $value['date']];
            }
            $group[$value['date']]['items'][] = $value;
        }
        $group = array_values($group);
        return $this->list_success($group);
    }

    /**
     * 圈子
     * @author liubo <liubo@ilongyuan.com.cn>
     */
    private function circle($p = 1, $limit = 10)
    {
        $params = [
            'uid'   => $this->uid,
            'page'  => $p,
            'count' => $limit
        ];
        $res = event('LocalClient')->doRequest('circle', $params, 'get');
        if ($res['code'] == 200) {
            return $res['data'];
        }
        return false;
    }

    /**
     * 格式化数据
     * @author liubo <liubo@ilongyuan.com.cn>
     * @param  [type] $data [description]
     */
    private function _format($data)
    {
        $list = [];
        foreach ($data as $value) {
            switch ($value['object_type']) {
                case 0:
                    // 视频
                    $obj = $this->_format_video($value['object_id']);
                    if (!$obj) {
                        continue;
                    }
                    $type = 'video';
                    if (isset($value['pub_time'])) {
                        $timestamp = strval($value['pub_time']);
                    } else {
                        $timestamp = strval($video['baseinfo']['create_time']);
                    }
                    break;
                case 1:
                    // 比赛
                    $obj = $this->_format_race($value['object_id']);
                    if (!$obj) {
                        continue;
                    }
                    $type = 'race';
                    if (isset($value['pub_time'])) {
                        $timestamp = strval($value['pub_time']);
                    } else {
                        $timestamp = strval(strtotime($race['baseinfo']['race_time']));
                    }
                    break;
                case 2:
                    // 新闻
                    $obj = $this->_format_news($value['object_id']);
                    if (!$obj) {
                        continue;
                    }
                    $type = 'news';
                    if (isset($value['pub_time'])) {
                        $timestamp = strval($value['pub_time']);
                    } else {
                        $timestamp = strval($news['baseinfo']['create_time']);
                    }
                    break;
                default:
                    continue;
            }
            $list[] = [
                'data' => $obj,
                'type' => $type,
                'timestamp' => $timestamp,
            ];
        }
        return $list;
    }

    /**
     * 格式化视频数据
     * @author liubo <liubo@ilongyuan.com.cn>
     * @param  [type] $vid [description]
     * @return [type]      [description]
     */
    private function _format_video($vid)
    {
        $video = event('Video')->detail($vid, $this->uid, true);
        if (empty($video)) {
            return false;
        }
        $liker = event('Like')->userlist(['target_id' => $vid, 'type' => 0]);
        $comments = event('Comments')->lists(['video_id' => $vid], 1, 4);
        return ['baseinfo' => $video, 'comments' => $comments, 'liker' => $liker];
    }

    /**
     * 格式化比赛数据
     * @author liubo <liubo@ilongyuan.com.cn>
     * @param  [type] $rid [description]
     * @return [type]      [description]
     */
    private function _format_race($rid)
    {
        $race = event('RaceGroup')->info($rid);
        $race['score'] = !empty($race['score']) ? array_map('intval', explode('-', $race['score'])) : [];

        // $fieldMap = array('id', 'title', 'subtitle', 'race_date', 'race_hour', 'score', 'team', 'list', 'game', 'match');
        // $race = $this->field_filter($race, $fieldMap);
        $vService = service('Video');
        $map = [
            'group_id' => $rid,
            'status'   => $vService::STATUS_PASS,
            'type'     => $vService::TYPE_MATCH
        ];
        $race['races'] = $vService->where($map)->order('round asc')->getField('id', true);
        if (empty($race['races'])) {
            return false;
        }
        $race_id = intval($race['races'][0]);
        $comments = event('Comments')->lists(['video_id' => $race_id], 1, 4);
        return ['baseinfo' => $race, 'comments' => $comments];
    }

    /**
     * 格式化资讯数据
     * @author liubo <liubo@ilongyuan.com.cn>
     * @param  [type] $nid [description]
     * @return [type]      [description]
     */
    private function _format_news($nid)
    {
        $news = event('News')->detail($nid, false);
        if (empty($news)) {
            return false;
        }
        $news['images'] = [];
        unset($news['game']);
        foreach ($news['content'] as $value) {
            if ($value['type'] == 'image') {
                $news['images'][] = $value['data'];
            }
            if (count($news['images']) >= 9) {
                break;
            }
        }
        $comments = event('NewsComments')->get($nid, false, 1, 2, $total);
        $news['statis']['comment'] = $total;
        return ['baseinfo' => $news, 'comments' => $comments];
    }
}